// categoryDetail.js 品类二级详情页面
var shihan = require('../../common/fetch')
var config = require('../../common/config')
var app = getApp()
var listflag = true
var winScale = 750 / app.data.deviceInfo.windowWidth
var range
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lastX: 0,
    lastY: 0,
    start: 1,
    count: 10,
    page: 1,
    page_size: 10,
    startprice: '',
    endprice: '',
    promotion_type: '',
    categorygoods: [],
    tabopacity: 'none',
    filterConflag: false,
    hasMore: true,
    listflag: true,
    showLoading: true,
    categoryflag: true,
    stopScrolll: false,
    categorys_fold: false,
    categorydetail: '',
    selectactive: '',
    currentTab: 0,
    catefoldflag: 0,
    totalflag: "active",
    salesflag: "",
    priceflag: "",
    priceimg: "",
    sort: '',
    cids: '',
    brand_ids: '',
    attributes: '',
    categorys: '',
    isrefresh: true,
    backToTop: false, // 返回顶部
    bottomimgflag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this, brandlist;
    that.setData({
      catalog_topcid: options.topcid,
      catalog_type: options.type,
      catalog_cid: options.cid || '',
      catalog_bid: options.bid || '',
      category_id: options.cid || options.bid
    })
    that.searchcateory(1);
    range = 660 / winScale
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        promotefresh: false
      })
    }
  },
  onNavbarTap: function(e) {
    listflag = true
    this.setData({
      showLoading: true,
      currentTab: e.currentTarget.dataset.index,
      categorygoods: [],
      page: 1,
      start: 1,
      totalflag: "active",
      salesflag: "",
      priceflag: "",
      priceimg: '',
      sort: '',
      startprice: '',
      endprice: '',
      cids: '',
      brand_ids: '',
      attributes: '',
      fliterflag: '',
      catefoldflag: 0,
      isrefresh: true,
      categoryflag: true,
      filterConflag: false,
      bottomimgflag: false,
      navbarleft: ((e.currentTarget.dataset.index + 1) * 130 - 287) / winScale
    });
    if (this.data.catalog_type==1) {
      this.setData({
        catalog_bid: e.currentTarget.dataset.goodid,
      })
    } else {
      this.setData({
        catalog_cid: e.currentTarget.dataset.goodid
      })
    }
    this.searchcateory()
  },
  openstoredetail: function(e) {
    wx.navigateTo({
      url: '/pages/storedetail/storedetail?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type
    })
  },
  opencatesort: function() {
    if (!this.data.catefoldflag) {
      this.setData({
        catefoldflag: 1,
        filterConflag: true
      })
    } else {
      this.setData({
        catefoldflag: 0,
        filterConflag: false
      })
    }
  },
  // 滚动计算滚动条距离
  onScroll: function(ev) {
    var scrollTop = ev.detail.scrollTop;
    if (scrollTop > (288 / winScale)) {
      this.setData({
        tabopacity: 'block'
      });
    } else {
      this.setData({
        tabopacity: 'none'
      });
    }
    if (scrollTop > 200) {
      this.setData({
        backToTop: true
      });
    } else {
      this.setData({
        backToTop: false
      });
    }
  },
  onBackToTop: function() {
    this.setData({
      backToTop: false,
      scrollTop: 0
    })
  },
  changetotal: function() { //综合
    var that = this
    that.setData({
      totalflag: "active",
      salesflag: "",
      priceflag: "",
      priceimg: '',
      sort: '',
      page: 1,
      start: 1,
      isrefresh: true,
      categoryflag: true,
      showLoading: true,
      categorygoods: [],
      bottomimgflag: false
    })
    this.searchcateory()
  },
  changesales: function() { //销量
    var that = this
    that.setData({
      totalflag: "",
      salesflag: "active",
      priceflag: "",
      priceimg: '',
      sort: 'hot',
      page: 1,
      start: 1,
      isrefresh: true,
      categoryflag: true,
      showLoading: true,
      categorygoods: [],
      bottomimgflag: false
    })
    this.searchcateory()
  },
  toggle: function() { //价格
    var that = this
    that.setData({
      totalflag: "",
      salesflag: "",
      priceflag: "active",
      page: 1,
      start: 1,
      isrefresh: true,
      categoryflag: true,
      showLoading: true,
      categorygoods: [],
      bottomimgflag: false
    })
    if (!that.data.priceimg) {
      that.setData({
        priceimg: "top",
        sort: 'price_asc'
      })
    } else if (that.data.priceimg == "top") {
      that.setData({
        priceimg: "down",
        sort: 'price_desc'
      })
    } else {
      that.setData({
        priceimg: "top",
        sort: 'price_asc'
      })
    }
    this.searchcateory()
  },
  changefliter: function() {
    this.animation.translateX(-range).step();
    this.setData({
      stopScrolll: true,
      filterConflag: true,
      animationData: this.animation.export()
    })
  },
  otherclosefilter: function() {
    this.animation.translateX(range).step();
    this.setData({
      catefoldflag: 0,
      filterConflag: false,
      stopScrolll: false,
      animationData: this.animation.export()
    })
  },
  closefilter: function() {
    var str = '', arra = {}, arrb = [], arrc = [], arrd = [], selsecflag = false, 
    bigarr = this.data.searchGoodsList, cate = this.data.catalog_type==1?'sh_cid':'sh_id';
    if (bigarr.sh_attributes) {
      for (var i = 0; i < bigarr.sh_attributes.length; i++) {
        // console.log(bigarr.sh_attributes[i].sh_attribute_id);
        for (var j = 0; j < bigarr.sh_attributes[i].sh_options.length; j++) {
          if (bigarr.sh_attributes[i].sh_options[j].active == 'active') {
            arrb.push(bigarr.sh_attributes[i].sh_options[j].sh_value);
            arra[bigarr.sh_attributes[i].sh_attribute_id] = arrb.join()
            selsecflag = true
          }
        }
        arrb.length = 0;
      }
    }
    if (bigarr.sh_promotions) {
      for (var m = 0; m < bigarr.sh_promotions.length; m++) {
        if (bigarr.sh_promotions[m].active == 'active') {
          selsecflag = true
          arrc.push(bigarr.sh_promotions[m].sh_id)
        }
      }
    }
    if (this.data.categorys) {
      for (var a = 0; a < this.data.categorys.length; a++) {
        if (this.data.categorys[a].active == 'active') {
          arrd.push(this.data.categorys[a][cate])
        }
      }
    }
    if (arrd.length>0) {
      if (this.data.catalog_type == 1) {
        this.setData({
          cids: arrd.join(',')
        })
      } else {
        this.setData({
          brand_ids: arrd.join(',')
        })
      }
    }
    this.animation.translateX(range).step();
    this.setData({
      categoryflag: false,
      filterConflag: false,
      stopScrolll: false,
      start: 1,
      promotion_type: arrc.join(','),
      attributes: JSON.stringify(arra),
      categorygoods: [],
      bottomimgflag: false,
      animationData: this.animation.export()
    })
    if (selsecflag || this.data.startprice || this.data.endprice) {
      this.setData({
        fliterflag: 'active',
        showLoading: true
      })
    } else {
      this.setData({
        fliterflag: '',
        showLoading: true
      })
    }
    this.searchcateory();
  },
  selectfilter: function(e) {
    var that = this;
    var big = e.currentTarget.dataset.a;
    var small = e.currentTarget.dataset.b;
    var filtertype = e.currentTarget.dataset.type;
    var activeitem = that.data.searchGoodsList.sh_attributes[big].sh_options[small]
    if (filtertype == 'attribute') {
      if (activeitem.active == '') {
        activeitem.active = 'active';
      } else {
        activeitem.active = '';
      }
    } else if (filtertype == 'promotions') {
      var activeitem = that.data.searchGoodsList
      var vname = e.currentTarget.dataset.vname
      if (activeitem[vname][big].active == '') {
        activeitem[vname][big].active = 'active';
      } else {
        activeitem[vname][big].active = '';
      }
    } else if (filtertype == 'categorys') {
      if (that.data.categorys[big].active == '') {
        that.data.categorys[big].active = 'active'
      } else {
        that.data.categorys[big].active = ''
      }
    }
    this.setData({
      categorys: that.data.categorys,
      searchGoodsList: that.data.searchGoodsList
    })
  },
  addactive: function(param) {
    if (param.sh_attributes) {
      for (var i = 0; i < param.sh_attributes.length; i++) {
        for (var j = 0; j < param.sh_attributes[i].sh_options.length; j++) {
          param.sh_attributes[i].sh_options[j].active = ''
          param.sh_attributes[i].foldflag = false
        }
      }
    }
    if (param.sh_promotions) {
      for (var a = 0; a < param.sh_promotions.length; a++) {
        param.sh_promotions[a].active = ''
        param.sh_promotions[0].foldflag = false
      }
    }
    if (param.sh_brands) {
      for (var b = 0; b < param.sh_brands.length; b++) {
        param.sh_brands[b].active = ''
      }
    }
    if (param.sh_categorys) {
      for (var c = 0; c < param.sh_categorys.length; c++) {
        param.sh_categorys[c].active = ''
      }
    }
    this.setData({
      categorys: this.data.catalog_type == 1 ? (param.sh_categorys) : (param.sh_brands),
      searchGoodsList: this.data.searchGoodsList
    })
  },
  numbergit: function(e) {
    var leveal = e.currentTarget.dataset.leveal;
    if (leveal == 'height') {
      this.setData({
        startprice: e.detail.value
      })
    } else if (leveal == 'low') {
      this.setData({
        endprice: e.detail.value
      })
    }
    console.log(this.data)
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id + '&category=' + this.data.productcategory
    })
  },
  goodsloadMoreData: function() {
    if (this.data.listflag) {
      this.setData({
        listflag: false,
        page: this.data.page + 1
      })
      this.searchcateory()
    }
  },
  dropsorting: function(e) {
    var index = e.currentTarget.dataset.index
    var type = e.currentTarget.dataset.type
    if (type == 'attributes') {
      if (this.data.searchGoodsList.sh_attributes[index].foldflag == false) {
        this.data.searchGoodsList.sh_attributes[index].foldflag = true
      } else {
        this.data.searchGoodsList.sh_attributes[index].foldflag = false
      }
    } else if (type == 'categorys') {
      this.setData({
        categorys_fold: !this.data.categorys_fold
      });
    }
    this.setData({
      searchGoodsList: this.data.searchGoodsList
    });
  },
  resetfilter: function() {
    this.setData({
      startprice: '',
      endprice: '',
      sort: '',
      cids: '',
      brand_ids: '',
      attributes: ''
    })
    this.searchcateory();
    this.addactive(this.data.searchGoodsList);
  },
  searchcateory: function(is_scroll) {
    var that = this
    // top_cid 一级分类id 必填 type 进入类型 0代表分类进行 1代表品牌进来 cid 选择的二级分类id
    // bid 选择的品牌id attributes 筛选属性规格 brand_ids 多筛选品牌 cids 多筛选分类 
    // page 当前页 page_size 每页数量   is_scroll 头部分类是否要滚动
    var data = '?top_cid=' + that.data.catalog_topcid 
      + '&type=' + that.data.catalog_type 
      + '&cid=' + that.data.catalog_cid 
      + '&bid=' + that.data.catalog_bid
      + '&sort=' + that.data.sort
      + '&cids=' + that.data.cids
      + '&brand_ids=' + that.data.brand_ids
      + '&attributes=' + that.data.attributes
      + '&page=' + that.data.page 
      + '&page_size=' + that.data.page_size;
    shihan.sendRequest(config.category_search_product_list + data, 'GET', {}, {})
      .then(function (response) {
        if (response.data.code == 0) {
          // console.log(response.data.data)
          if (that.data.page == 1 && that.data.isrefresh) {
            var windowres = wx.getSystemInfoSync()
            response.data.data.sh_top_arr.unshift({
              sh_id: '0',
              sh_name: "全部商品"
            });
            that.setData({
              isrefresh: false,
              winHeight: windowres.windowHeight,
              category_search: response.data.data,
              searchGoodsList: response.data.data.sh_items,
              productcategory: response.data.data.sh_title_name
            })
            that.addactive(that.data.searchGoodsList);
            wx.setNavigationBarTitle({
              title: that.data.category_search.sh_title_name
            })
            
            if (is_scroll && is_scroll==1) {
              for (var i = 0; i < that.data.category_search.sh_top_arr.length; i++) {
                that.data.category_search.sh_top_arr[i].index = i;
                if (that.data.category_search.sh_top_arr[i].sh_id == that.data.category_id) {
                  that.setData({
                    currentTab: i,
                    navbarleft: (i == 0) ? 0 : (((i + 1) * 130 - 287) / winScale)
                  });
                }
              }
            }
          }
          
          if (response.data.data.sh_items.sh_products.length>0) {
            for (var i = 0; i < response.data.data.sh_items.sh_products.length; i++) {
              if (response.data.data.sh_items.sh_products[i].sh_label.sh_location) {
                var pos = response.data.data.sh_items.sh_products[i].sh_label
                pos['posa'] = pos.sh_location.split('_')[0];
                pos['posb'] = pos.sh_location.split('_')[1];
              }
            }
            that.setData({
              hasMore: true,
              listflag: true,
              categorygoods: that.data.categorygoods.concat(response.data.data.sh_items.sh_products),
            })
          } else {
            that.setData({
              listflag: false,
              hasMore: false
            })
          }
          if (that.data.categorygoods.length == response.data.data.sh_items.sh_total) {
            that.setData({
              listflag: false,
              hasMore: false
            })
          }
        } else {
          that.setData({
            listflag: false,
            hasMore: false
          })
        }
        that.setData({
          showLoading: false
        })
      }, function (error) {
        console.log(error);
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  goodsloadMoreData: function () {
    if (this.data.listflag) {
      this.setData({
        listflag: false,
        page: this.data.page + 1
      })
      this.searchcateory();
    }
  }
})